<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\AfterSaleAddress;
use App\Product_order_after_sale;
use App\Shop;
use App\Product_order;

class AddressController extends AdminController
{

    // 添加
    public function add(Request $request)
    {
        $newAddress = new AfterSaleAddress();
        $attrs = array(
            'name',
            'address',
            'username',
            'userphone'
        );
        foreach ($attrs as $attr) {
            $newAddress->$attr = trim($request->input($attr, ''));
        }
        if ($newAddress->save()) {
            $this->output($newAddress->toArray());
        } else {
            $this->err('保存错误');
        }
    }

    // 更新
    public function update(Request $request)
    {
        $id = trim($request->input('id'));
        
        $newAddress = AfterSaleAddress::where('id', $id)->first();
        $attrs = array(
            'name',
            'address',
            'username',
            'userphone'
        );
        foreach ($attrs as $attr) {
            $newValue = trim($request->input($attr, ''));
            if ($newValue) {
                $newAddress->$attr = $newValue;
            }
        }
        if ($newAddress->save()) {
            $this->output($newAddress->toArray());
        } else {
            $this->err('保存错误');
        }
    }

    // 设置默认
    public function setdefault(Request $request)
    {
        $id = trim($request->input('id'));
        AfterSaleAddress::where('default', 1)->update([
            'default' => 0
        ]);
        $newAddress = AfterSaleAddress::where('id', $id)->first();
        $newAddress->default = 1;
        if ($newAddress->save()) {
            $this->output($newAddress->toArray());
        } else {
            $this->err('保存错误');
        }
    }

    // 删除
    public function del(Request $request)
    {
        $id = trim($request->input('id'));
        $newAddress = AfterSaleAddress::where('id', $id)->first();
        if ($newAddress->delete()) {
            $this->output('删除成功');
        } else {
            $this->err('删除错误');
        }
    }

    // 列表
    public function alist(Request $request)
    {
        $afterid = trim($request->input('id'));
        $data = array();
        if($afterid){
            $after = Product_order_after_sale::where('id', $afterid)->first();
            $order = Product_order::where('order_id', $after->order_id)->first();
            $shop = Shop::where('member_id', $order->member_id)->first();
            $data[]= array(
                "address"=>$shop->after_address,  
                "id"=> 0,
                "name"=>"商铺默认地址", 
                "username"=>$shop->after_username,
                "userphone"=> $shop->after_userphone
            );
        }
        $items = AfterSaleAddress::orderBy('default', 'desc')->get();
        foreach ($items as $item) {
            $data[] = $item->toArray();
        }
        $this->output($data);
    }
}